//编辑，详情动态表格
<template>
  <div>
    <el-dialog
      v-el-drag-dialog="{minWidth: 750, updataFull, updataDialogWidth}"
      :fullscreen="isfullscreen"
      :append-to-body="true"
      :width="setDialogWidth('90%')"
      :visible="visible"
      :title="$t('START_LOCATING_FAULT')"
      @open="open"
      @close="close"
    >
      <div class="flex flex-wrap">
        <div class="w-50 mb-10">
          {{ $t('FAULTY_SERVICE_NAME') }}：
          {{ bizOpenData.bizName }}
        </div>
        <div class="w-50 mb-10">
          {{ $t('FAULT_SERVICE_CODE') }}：
          {{ bizOpenData.resourceCode }}
        </div>
        <div class="w-50 mb-10">
          {{ $t('ORIGINAL_BUSINESS') + $t('A_END_STATION') }}：
          {{ getRegionName(bizOpenData.startStationId) }}
        </div>
        <div class="w-50 mb-10">
          {{ $t('ORIGINAL_BUSINESS') + $t('Z_END_STATION') }}：
          {{ getRegionName(bizOpenData.endStationId) }}
        </div>
        <div class="w-50 mb-10">
          {{ $t('ORIGINAL_BUSINESS') + $t('ANODE') }}：
          {{ bizOpenData.startNode ? bizOpenData.startNode.nodeName : '' }}
        </div>
        <div class="w-50 mb-10">
          {{ $t('ORIGINAL_BUSINESS') + $t('ZNODE') }}：
          {{ bizOpenData.endNode ? bizOpenData.endNode.nodeName : '' }}
        </div>
      </div>
      <el-table
        v-if="tableHead.length"
        ref="tableBox"
        class="page-cutover fault-location"
        border
        :data="segmentList"
        style="width: 100%"
        size="mini"
      >
        <template slot="empty">
          <NullData />
        </template>
        <el-table-column
          type="index"
          :label="$t('SEQUENCE')"
          fixed="left"
          :width="resetSize(60)"
          align="center"
        />
        <div v-for="(item, index) in tableHead" :key="index">
          <el-table-column :label="item.segmentName" align="center" show-overflow-tooltip>
            <el-table-column
              :label="item.startNode ? item.startNode.nodeName : '--'"
              align="center"
              :prop="`segmentList${index}.startPort.bizName`"
              show-overflow-tooltip
              min-width="150"
            >
              <template v-slot="scope">
                <div class="port-item fr">
                  <span>
                    {{ scope.row[`segmentList${index}`].startPort.bizName }}
                  </span>
                  <div
                    v-if="
                      scope.row[`segmentList${index}`].startPortCategory === 'VARIABLE_POINT' &&
                        afsList.indexOf(scope.row[`segmentList${index}`].startNodeId) !==
                        afsList.length - 1
                    "
                    class="flex-column"
                  >
                    <el-checkbox
                      v-model="scope.row[`segmentList${index}`].startPort.checked"
                      :disabled="
                        disabledStatus(scope.row[`segmentList${index}`].startPort, scope.row)
                      "
                      :title="disabledMsg(scope.row[`segmentList${index}`].startPort)"
                    />
                    <i
                      v-if="!disabledStatus(scope.row[`segmentList${index}`].startPort, scope.row)"
                      class="el-icon-document"
                      @click="portClick(scope.row[`segmentList${index}`].startPort)"
                    />
                  </div>
                  <i
                    v-if="scope.row[`segmentList${index}`].startPort.checked"
                    class="iconfont icon-AFSss-lux right-light"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column
              v-if="item.cable"
              :label="item.cable ? item.cable.cableName : '--'"
              :prop="`segmentList${index}.fiber.fiberName`"
              align="center"
              min-width="150"
              show-overflow-tooltip
            />
            <el-table-column
              :label="item.endNode ? item.endNode.nodeName : '--'"
              align="center"
              :prop="`segmentList${index}.endPort.bizName`"
              show-overflow-tooltip
              min-width="150"
            >
              <template v-slot="scope">
                <div class="port-item fr">
                  <i
                    v-if="scope.row[`segmentList${index}`].endPort.checked"
                    class="iconfont icon-AFSss-lux left-light"
                  />
                  <div
                    v-if="
                      scope.row[`segmentList${index}`].endPortCategory === 'VARIABLE_POINT' &&
                        afsList.indexOf(scope.row[`segmentList${index}`].endNodeId) !== 0
                    "
                    class="flex-column"
                  >
                    <el-checkbox
                      v-model="scope.row[`segmentList${index}`].endPort.checked"
                      :disabled="
                        disabledStatus(scope.row[`segmentList${index}`].endPort, scope.row)
                      "
                      :title="disabledMsg(scope.row[`segmentList${index}`].endPort)"
                    />
                    <i
                      v-if="!disabledStatus(scope.row[`segmentList${index}`].endPort, scope.row)"
                      class="el-icon-document"
                      @click="portClick(scope.row[`segmentList${index}`].endPort)"
                    />
                  </div>
                  <span>
                    {{ scope.row[`segmentList${index}`].endPort.bizName }}
                  </span>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
        </div>
      </el-table>
      <template v-slot:footer>
        <el-button @click="close">{{ $t('CLOSE') }}</el-button>
        <el-button type="primary" @click="$debounce(save)">{{ $t('TO_LOCATE') }}</el-button>
      </template>
    </el-dialog>
    <test-params
      :visible.sync="showParams"
      :cur-otdr-param="curOtdrParam"
      @saveParam="saveParam"
    />
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import faultLocationApi from '@/api/oen/FaultLocationApi'
  import logicSegmentApi from '@/api/oen/LogicSegmentApi'
  import otdrTest from '@/api/afs/OtdrTest'
  import afsInfo from '@/api/afs/AfsInfo'
  import TestParams from './components/otdrTest/TestParams'
  import { deepClone } from '@/utils/common'

  export default {
    name: 'FaultLocation',
    components: { TestParams },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      rowData: {
        type: Object,
        default: () => {}
      },
      locationData: {
        type: Object,
        default: () => {},
        required: true
      }
    },
    inject: ['functionName', 'parentVM'],
    data() {
      return {
        segmentList: [],
        curPortData: {},
        curOtdrParam: {},
        defaultOtdrParam: {
          cut: true,
          testMode: 'AVG',
          waveLength: 1550,
          pulseWidth: 80,
          testRange: 8000,
          lossThreshold: 0.2,
          reflectThreshold: -40,
          endThreshold: 10,
          fixParam: 1,
          refractRate: 1.472,
          testNum: 5
        },
        bizOpenData: {},
        showParams: false,
        portParamData: {},
        tableHead: [],
        afsList: [],
        channelMergeList: [],
        otdrModelInfo: {},
        afsStatus: {},
        afsPassStatus: [
          'TRANSFER',
          'OTDR_TRANSFER',
          'OTDR_TEST',
          'OTDR_RESTORE',
          'MOTION',
          'UNPLUG',
          'IDLE',
          'LOWER_POWER',
          'STANDBY',
          'LOW_POWER',
          'READY',
          'CANCEL',
          'DISABLE'
        ]
      }
    },
    computed: {
      ...mapGetters(['baseRegionList'])
    },
    methods: {
      open() {
        this.segmentList = []
        this.tableHead = []
        this.afsList = []
        const res = deepClone(this.locationData)
        this.bizOpenData = { ...res.bizOpen }
        this.channelMergeList = deepClone(res.channelMergeList)
        const channelMergeList = res.channelMergeList
        const afsPorts = []
        channelMergeList.forEach((i, iIndex) => {
          i.segmentChannelList.forEach((j, index) => {
            j.startPort.checked = false
            j.endPort.checked = false
            j.startPort.bizName = this.$utils.handleServiceI18n(j.startPort.bizName)
            j.endPort.bizName = this.$utils.handleServiceI18n(j.endPort.bizName)
            if (j.startPortCategory === 'VARIABLE_POINT') {
              afsPorts.push(j.startPort)
              j.startPort.otdrParam = null
              if (iIndex === 0) {
                this.afsList.push(j.startNodeId)
              }
            }
            if (j.endPortCategory === 'VARIABLE_POINT') {
              j.endPort.otdrParam = null
              afsPorts.push(j.endPort)
            }
            i['segmentList' + index] = j
          })
        })
        this.segmentList = channelMergeList
        this.tableHead = this.correctOrder(res.networkSegmentList)
        this.getAfsStatus(afsPorts)
        this.getOtdrModelInfo(afsPorts)
        this.getOtdrParam(afsPorts)
      },
      // 端口可选择状态
      disabledStatus(port, row) {
        // console.log('row', row)
        const logicChannel = row.logicChannel.segmentList.find(
          i => i.startPortId === port.portId || i.endPortId === port.portId
        )
        const firstSegment = logicChannel.physicStruct[0]
        const lastSegment = logicChannel.physicStruct[logicChannel.physicStruct.length - 1]
        const afsStatus =
          this.afsPassStatus.includes(this.afsStatus[firstSegment.startPort.deviceId]) &&
          this.afsPassStatus.includes(this.afsStatus[lastSegment.endPort.deviceId])
        return (
          !this.portParamData[port.portId] ||
          !this.otdrModelInfo[port.deviceId] ||
          !afsStatus ||
          logicChannel.startNodeId === logicChannel.endNodeId
        )
      },
      // 端口不可选择状态提示
      disabledMsg(port) {
        let msg = ''
        // 没有测试参数
        if (!this.portParamData[port.portId]) {
          msg = this.$t('NO_TEST_RECORDS')
        }
        // 没有OTDR模块
        if (!this.otdrModelInfo[port.deviceId]) {
          msg = this.$t('NO_OTDR_MODULE')
        }
        // AFS状态
        if (!this.afsPassStatus.includes(this.afsStatus[port.deviceId])) {
          msg = this.$t('NOT_FREE')
        }
        return msg
      },
      // 表头反向纠正
      correctOrder(data) {
        return data.reduce((prev, curr, index) => {
          let start = 'start'
          let end = 'end'
          if (index !== 0 && prev[index - 1].endNodeId !== curr.startNodeId) {
            start = 'end'
            end = 'start'
          }
          const item = {
            ...curr,
            startNode: curr[start + 'Node'],
            startNodeCategory: curr[start + 'NodeCategory'],
            startNodeId: curr[start + 'NodeId'],
            startStationId: curr[start + 'StationId'],
            endNode: curr[end + 'Node'],
            endNodeCategory: curr[end + 'NodeCategory'],
            endNodeId: curr[end + 'NodeId'],
            endStationId: curr[end + 'StationId']
          }
          prev.push(item)
          return prev
        }, [])
      },
      // 获取afs设备状态
      getAfsStatus(afsPorts) {
        this.afsStatus = {}
        afsInfo
          .checkDeviceStatus({
            deviceIds: Array.from(new Set(afsPorts.map(i => i.deviceId))).join()
          })
          .then(res => {
            const afsStatus = {}
            res.forEach(i => {
              if (i.protect) {
                afsStatus[i.deviceId] = 'PROTECT'
                return
              }
              if (i.onlineStatus === 'OFFLINE') {
                afsStatus[i.deviceId] = i.lowPowerType === 'LOW_POWER' ? 'LOW_POWER' : 'OFFLINE'
              } else {
                afsStatus[i.deviceId] = i.afsStatus
              }
            })
            this.afsStatus = afsStatus
            this.$refs.tableBox.doLayout()
          })
      },
      // 查询每个端口所属设备是否有ot测试模块
      getOtdrModelInfo(afsPorts) {
        this.otdrModelInfo = {}
        if (afsPorts.length === 0) return
        otdrTest
          .deviceOtdrInstallInfo({
            deviceIds: Array.from(new Set(afsPorts.map(i => i.deviceId)))
          })
          .then(res => {
            this.otdrModelInfo = res || {}
            this.$refs.tableBox.doLayout()
          })
      },
      // 获取每个端口的测试参数
      getOtdrParam(afsPorts) {
        this.portParamData = {}
        faultLocationApi
          .otdrParam({
            portIdList: afsPorts.map(i => i.portId).join()
          })
          .then(res => {
            this.portParamData = res || {}
            this.$refs.tableBox.doLayout()
          })
      },
      // 测试参数点击
      portClick(data) {
        this.curPortData = data
        const otdrParam = data.otdrParam || this.portParamData[data.portId] || this.defaultOtdrParam
        this.curOtdrParam = { ...otdrParam }
        this.showParams = true
      },
      saveParam(data) {
        this.curPortData.otdrParam = data
        this.showParams = false
      },
      // 获取区域/站点/机房
      getRegionName(stationId) {
        const stationData = this.baseRegionList.find(i => i.regionId === stationId)
        return stationData ? stationData.regionName : ''
      },
      async save() {
        const selectedPorts = []
        this.segmentList.forEach(i => {
          let physicStruct = []
          i.segmentChannelList.forEach((j, index) => {
            physicStruct.push(j.segmentId)
            if (j.startPort.checked) {
              selectedPorts.push({
                deviceId: j.startNodeId,
                portId: j.startPortId,
                physicStruct: physicStruct,
                testDirection: 'Z',
                otdrParam:
                  j.startPort.otdrParam ||
                  this.portParamData[j.startPortId] ||
                  this.defaultOtdrParam
              })
            }
            if (j.endPort.checked) {
              selectedPorts.push({
                deviceId: j.endNodeId,
                portId: j.endPortId,
                physicStruct: physicStruct,
                testDirection: 'A',
                otdrParam:
                  j.endPort.otdrParam || this.portParamData[j.endPortId] || this.defaultOtdrParam
              })
            }
            if (j.endPortCategory === 'VARIABLE_POINT') {
              physicStruct = []
            }
          })
        })
        if (selectedPorts.length === 0) {
          this.$message.error(this.$t('PLEASE_SELECT') + this.$t('PORT'))
          return
        }
        const structQueryData = {}
        selectedPorts.forEach(i => {
          structQueryData[i.portId] = i.physicStruct
        })
        const linkSegmentList = await logicSegmentApi.getByStructMap(structQueryData)
        selectedPorts.forEach(i => {
          i.linkSegmentId = linkSegmentList[i.portId]
          delete i.physicStruct
        })
        // console.log('selectedPorts', selectedPorts)
        const queryData = {
          bizName: this.rowData.bizName,
          bizId: this.rowData.bizId,
          channelMergeList: this.channelMergeList,
          testParamList: selectedPorts,
          networkSegmentList: this.tableHead,
          functionName: this.parentVM.functionName || this.functionName
        }
        faultLocationApi.start(queryData).then(res => {
          if (res) {
            this.$message.success(this.$t('OPERATE_SUCCESS'))
            this.close()
          } else {
            this.$message.error(this.$t('OPERATEFAILED'))
          }
        })
      },
      close() {
        this.$emit('close')
      }
    }
  }
</script>
<style scoped lang="scss">
  @import 'src/assets/css/mixin.module';
  .fault-location {
    .port-item {
      & > .flex-column {
        width: 30px;

        .el-icon-document {
          cursor: pointer;
        }
      }
    }

    .right-light {
      position: absolute;
      right: 0px;
      transform: rotate(-135deg);
      @include themeify {
        color: lighten(themed('textColor'), 10%);
      }
    }
    .left-light {
      position: absolute;
      left: 0px;
      transform: rotate(45deg);
      @include themeify {
        color: lighten(themed('textColor'), 10%);
      }
    }
  }
</style>
